package com.maomao.admin.service.system.impl;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.maomao.admin.domain.core.vo.TableDataInfo;
import com.maomao.admin.domain.system.entry.*;
import com.maomao.admin.persistence.repository.SysDictDataRepository;
import com.maomao.admin.persistence.repository.SysDictTypeRepository;
import com.maomao.admin.service.system.AbstractPageService;
import com.maomao.admin.service.system.ISysDictTypeService;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.maomao.admin.common.constant.UserConstants;
import com.maomao.admin.common.exception.ServiceException;
import com.maomao.admin.common.utils.StringUtils;

/**
 * 字典 业务层处理
 *
 * @author mao.kaiyin
 */
@Service
public class SysDictTypeServiceImpl extends AbstractPageService implements ISysDictTypeService {

    @Autowired
    private SysDictTypeRepository dictTypeRepository;

    @Autowired
    private SysDictDataRepository dictDataRepository;

    @Resource
    private JPAQueryFactory queryFactory;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }


    private JPAQuery<SysDictType> getSysDictTypeQuery(SysDictType dictType) {
        JPAQuery<SysDictType> jpaQuery = queryFactory.selectFrom(QSysDictType.sysDictType);
        List<Predicate> predicates = new ArrayList<>();
        if (StringUtils.isNotBlank(dictType.getDictName())) {
            predicates.add(QSysDictType.sysDictType.dictName.contains(dictType.getDictType()));
        }
        if (StringUtils.isNotBlank(dictType.getStatus())) {
            predicates.add(QSysDictType.sysDictType.status.eq(dictType.getStatus()));
        }
        if (StringUtils.isNotBlank(dictType.getDictType())) {
            predicates.add(QSysDictType.sysDictType.dictType.contains(dictType.getDictType()));
        }

        Map<String, Object> params = dictType.getParams();
        if (params != null) {
            Object beginTime = params.get("beginTime");
            if (beginTime instanceof Date) {
                predicates.add(QSysDictType.sysDictType.createTime.gt((Date) beginTime));
            }

            Object endTime = params.get("endTime");
            if (endTime instanceof Date) {
                predicates.add(QSysDictType.sysDictType.createTime.lt((Date) endTime));
            }
        }
        if (predicates.size() > 0) {
            jpaQuery.where(predicates.toArray(new Predicate[0])).fetch();
        }
        return jpaQuery;
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {
        JPAQuery<SysDictType> jpaQuery = this.getSysDictTypeQuery(dictType);
        return jpaQuery.fetch();
    }


    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public TableDataInfo<SysDictType> selectDictTypePage(SysDictType dictType) {
        JPAQuery<SysDictType> jpaQuery = this.getSysDictTypeQuery(dictType);
        return new TableDataInfo<>(jpaQuery.fetch(), jpaQuery.fetchCount());
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll() {
        return dictTypeRepository.findAll();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        return queryFactory.selectFrom(QSysDictData.sysDictData)
                .where(QSysDictData.sysDictData.status.eq("0")
                        .and(QSysDictData.sysDictData.dictType.eq(dictType)))
                .orderBy(QSysDictData.sysDictData.dictSort.asc()).fetch();
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return dictTypeRepository.findById(dictId).orElse(null);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType) {
        return dictTypeRepository.findByDictType(dictType);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        dictTypeRepository.deleteAllById(Arrays.asList(dictIds));
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        return;
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
//        DictUtils.clearDictCache();
        return;
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict) {
        dictTypeRepository.save(dict);
        return 0;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict) {
        dictTypeRepository.save(dict);
        return 0;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
//        SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType());
        SysDictType dictType = dictTypeRepository.findByDictType(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
